/*
 *  This sketch sends data via HTTP GET requests to data.sparkfun.com service.
 *
 *  You need to get streamId and privateKey at data.sparkfun.com and paste them
 *  below. Or just customize this script to talk to other HTTP servers.
 *
 */

#include <WiFi.h>
#include <aJSON.h>
#include <MPython.h>

double Vars;

const char* ssid     = "WLJY";
const char* password = "steam666";

const char* host = "www.bigiot.net";
const int httpPort = 8181;

unsigned long lastCheckInTime = 0; //记录上次报到时间
const unsigned long postingInterval = 40000; // 每隔40秒向服务器报到一次

//=============  此处必须修该============
String fs="2032"; // 你的设备编号   ==
String fss="7871"; // 你的设备编号   ==
String led="7872"; // 你的设备编号   ==
String leds="7873"; // 你的设备编号   ==
String door="2031"; // 你的设备编号   ==
String xyj="2000"; // 你的设备编号   ==

String DEVICEID="9159"; // 你的设备编号   ==
String  APIKEY = "58710677c"; // 设备密码==
//=======================================

void setup()
{
    Serial.begin(115200);
    delay(10);
    mPython.begin();
    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    display.setCursorXY(36,22);
    display.print(ssid);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
   delay(3000);
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
   
    pinMode(P0, OUTPUT);
   // pinMode(P1, OUTPUT);
   display.fillScreen(0);
   display.setCursorXY(16, 22);
   display.print("connected: OK");
   delay(1000);
}
WiFiClient client;

void loop()
{

while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  // Use WiFiClient class to create TCP connections
  if (!client.connected()) {
    if (!client.connect(host, httpPort)) {
      Serial.println("connection failed");
      delay(5000);
      return;
    }
  }

  if(millis() - lastCheckInTime > postingInterval || lastCheckInTime==0) {
    checkIn();
  }
  
  // Read all the lines of the reply from server and print them to Serial
  if (client.available()) {
    String inputString = client.readStringUntil('\n');
    inputString.trim();
    Serial.println(inputString);
    int len = inputString.length()+1;
    if(inputString.startsWith("{") && inputString.endsWith("}")){
      char jsonString[len];
      inputString.toCharArray(jsonString,len);
      aJsonObject *msg = aJson.parse(jsonString);
      processMessage(msg);
      aJson.deleteItem(msg);          
    }
  }
}

void processMessage(aJsonObject *msg){
  aJsonObject* method = aJson.getObjectItem(msg, "M");
  aJsonObject* content = aJson.getObjectItem(msg, "C");     
  aJsonObject* client_id = aJson.getObjectItem(msg, "ID");
  if (!method) {
    return;
  }
    String M = method->valuestring;
    if(M == "say"){
      String C = content->valuestring;
      String F_C_ID = client_id->valuestring;
      if(C == "play"){
          digitalWrite(P0, HIGH);
          //digitalWrite(P1, HIGH);
          display.fillScreen(0);
         display.setCursorXY(24, 22);
         display.print("LED: On");
        sayToClient(F_C_ID,"LED All on!");    
      }
      if(C == "stop"){
           digitalWrite(P0, LOW);
          //digitalWrite(P1, LOW);
          display.setCursorXY(24, 22);
         display.print("LED: OFF");
        sayToClient(F_C_ID,"LED All off!");    
      }
    }
}

void checkIn() {
    String msg = "{\"M\":\"checkin\",\"ID\":\"" + DEVICEID + "\",\"K\":\"" + APIKEY + "\"}\n";
    client.print(msg);
    lastCheckInTime = millis(); 
}

void sayToClient(String client_id, String content){
  String msg = "{\"M\":\"say\",\"ID\":\"" + client_id + "\",\"C\":\"" + content + "\"}\n";
  client.print(msg);
  lastCheckInTime = millis();
}
